package LeetCode.LinkedList;

import java.util.HashSet;
import java.util.Set;

/**
 * @author : LdLtd
 * @Date : 2023/7/29
 * @Description:141. 环形链表
 */
public class linked_list_cycle {
//      Definition for singly-linked list.
      class ListNode {
          int val;
          ListNode next;
          ListNode(int x) {
             val = x;
             next = null;
          }
      }

    public class Solution {
          /*哈希*/
        public boolean hasCycle(ListNode head) {
            Set<ListNode> seen = new HashSet<ListNode>();
            while (head != null) {
                if (!seen.add(head)) {
                    return true;
                }
                head = head.next;
            }
            return false;
        }
        /*双指针*/
        public boolean hasCycle1(ListNode head) {
            if(head==null||head.next==null){
                return false;
            }
            ListNode slow=head;
            ListNode fast=head.next;
            while(slow!=fast){
                if(fast==null||fast.next==null){
                    return false;
                }
                slow=slow.next;
                fast=fast.next.next;
            }
            return true;
        }
    }
}
